package com.wwwarehouse.common.tools;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.bean.PayResultBean;
import com.wwwarehouse.common.bean.WeChatBean;
import com.wwwarehouse.common.http.NoHttpUtils;

/**
 * Created by xiaoke.ni on 2017/7/24.
 */

public abstract class PayBaseUtil implements NoHttpUtils.OnResponseListener {

    public static final int PLUGIN_NOT_INSTALLED = -1;
    public static final int PLUGIN_NEED_UPGRADE = 2;
    public static final int UNIONPAY_REQUESTCODE = 1;
    private static final int SDK_PAY_FLAG = 1;

    private String sResultStatus;


    private Activity mContext;
    private AliPayListener aliPayListener;

    public PayBaseUtil(Activity mContext) {
        this.mContext = mContext;
    }

    /*********************************************  支   付    宝 ****************************************************/
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    //	同步返回的结果必须放置到服务端进行验证
                    PayResultBean sPayResult = new PayResultBean((String) msg.obj);
                    //	todo 同步返回的数据，对于商户在服务端没有收到异步通知的时候，可以依赖服务端对同步返回的结果来进行判断是否支付成功
                    sResultStatus = sPayResult.getResultStatus();
                    if (TextUtils.equals("9000", sResultStatus)) {
                        ToastUtils.showToast("支付成功");
                        if (aliPayListener != null)
                            aliPayListener.success();
//                        HashMap<Object, Object> hashMap = new HashMap<>();
//                        hashMap.put("memo", sPayResult.getMemo());
//                        hashMap.put("result", sPayResult.getResult());
//                        hashMap.put("resultStatus", sResultStatus);
//                        NoHttpUtils.httpPost(Constant.ALIPAY, hashMap, PayBaseUtil.this, 1);
                    } else if (TextUtils.equals("8000", sResultStatus)) {
                        ToastUtils.showToast("支付结果确认中");
                        if (aliPayListener != null)
                            aliPayListener.paying();
                    } else {
                        //ToastUtils.showToast("支付失败" + sResultStatus);
//						if (mVeryResultListener != null) {
//							mVeryResultListener.onFail();

                        ToastUtils.showToast("支付失败");
                        if (aliPayListener != null)
                            aliPayListener.failed();
                    }

                    break;
            }
        }
    };


    protected void parseData(final String payInfo) {
        if (payInfo == null) {
            ToastUtils.showToast("订单信息为空");
            return;
        }
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                //	构造payTask对象
                PayTask aliPay = new PayTask(mContext);
                //	调用支付接口, 获取支付结果
                String result = aliPay.payV2(payInfo, true).toString();
                Message msg = Message.obtain();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public interface AliPayListener {
        void success();

        void failed();

        void paying();
    }

    public void setAliPayListener(AliPayListener aliPayListener) {
        this.aliPayListener = aliPayListener;
    }

    /*********************************************  银   联 ****************************************************/
    protected void doStartUnionPayPlugin(Activity activity, String tn, String mode) {
        // mMode参数解释：
        // 0 - 启动银联正式环境
        // 1 - 连接银联测试环境
        int ret;
        ret = UPPayAssistEx.startPay(activity, null, null, tn, mode);

        if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
            // 需要重新安装控件

            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("提示");
            builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            UPPayAssistEx.installUPPayPlugin(mContext);
                            dialog.dismiss();
                        }
                    });

            builder.setPositiveButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();

        }
    }

    /*********************************************  微 信 支 付 ****************************************************/
    public void sendPayRequest(WeChatBean weChatBean) {
        IWXAPI mMsgApi;
        //商户APP工程中引入微信JAR包，调用API前，需要先向微信注册您的APPID
        mMsgApi = WXAPIFactory.createWXAPI(mContext, null);
//        mMsgApi.unregisterApp();
        // 将该app注册到微信
        mMsgApi.registerApp(BaseApplication.getApplicationInstance().getAPP_ID());//(appId申请得到)(企业版)
        PayReq req = new PayReq();
        if (weChatBean.getAppid() != null) {
            req.appId = weChatBean.getAppid();
        }
        req.partnerId = weChatBean.getPartnerid();
        req.prepayId = weChatBean.getPrepayid();
        req.nonceStr = weChatBean.getNoncestr();
        req.timeStamp = weChatBean.getTimestamp();
        req.packageValue = "Sign=WXPay";
        req.extData = "app data"; // optional
        req.sign = weChatBean.getSign();
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        LogUtils.showInfoLog("chenchao" + "\n" + "appId     " + weChatBean.getAppid() + "\n" + "parterId    " + weChatBean.getPartnerid() + "\n" + " prepayId     " + weChatBean.getPrepayid()
                + "\n" + "nonceStr     " + weChatBean.getNoncestr() + "\n" + "timeStamp     " + weChatBean.getTimestamp() + "\n" + "packageValue     " + "Sign=WXPay" + "\n" + "sign     " + weChatBean.getSign());
        //3.调用微信支付sdk支付方法
        mMsgApi.sendReq(req);

    }

}
